package com.project.shiro;

import com.project.bean.UserBean;
import com.project.service.IUserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.cache.MemoryConstrainedCacheManager;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class UserRealm extends AuthorizingRealm {
    @Autowired
    private IUserService userService;

    public UserRealm(){
        //定义凭证匹配器
        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
        // 设置加密算法
        matcher.setHashAlgorithmName("md5");
        //设置散列书
        matcher.setHashIterations(1024);
        //设置编码
        matcher.setStoredCredentialsHexEncoded(true);
        this.setCredentialsMatcher(matcher);
        //开去缓存管理
        this.setCacheManager( new MemoryConstrainedCacheManager());
//        //开启全局缓存
//        this.setCachingEnabled(true);
//        //身份认证缓存
//        this.setAuthenticationCachingEnabled(true);
//        //授权缓存
//        this.setAuthorizationCachingEnabled(true);
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //得到登录主体，由登录时，存放登录主体决定
        System.out.println("#####################################################");
        UserBean user =(UserBean) principalCollection.getPrimaryPrincipal();
        if (user !=null){
            SimpleAuthorizationInfo info =new SimpleAuthorizationInfo();
            user.getRoleBeans().forEach(n->{
                info.addRole(n.getName());
            });
            //添加权限
            user.getGradeBeans().forEach(n->{
                info.addStringPermission(n.getContent());
            });
            return info;
        }


        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //得到用户名
        String userName = authenticationToken.getPrincipal().toString();
        //得到用户名称
        UserBean user = userService.findByName(userName);
        if (user != null){
            return  new SimpleAuthenticationInfo(user,user.getPassword(), ByteSource.Util.bytes(user.getSalt()),this.getName());
        }
        return null;
    }
}
